package Servlet.Add;

import bean.userBean;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@WebServlet("/novelImageUploadDo")
public class novelImageUploadDo extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");		
		//java.io.PrintWriter out = response.getWriter();	
		String msg = "";	
		String novelNumber = "";
		String novelImage = "";
		String imageNew = "";	
		String action = "";
		String url = "novelImageUpload.jsp";
				
		try {
			HttpSession session = request.getSession();
			userBean user= (userBean) session.getAttribute("user");
			if (user == null || !user.getUserType().equals("admin")) {							//如果登录已失效，或权限不足
				msg = "图片没有更新。您的登录已失效。";
				msg += "（<a href='login.jsp' target='_top'>用户登录</a>）</p>";	//前往最外层的框架集，即整个浏览器窗口
				return;
			}	
			
			String path = request.getServletContext().getRealPath(""); //当前项目运行时所在的物理目录
			String uploadFolder = "novelImage/";					//存放文件的子目录
			path += uploadFolder; 												//文件存放的目录
			System.out.println(path);
			File folder = new File(path); 										//创建File对象
			
			if (folder.exists() == false) {										//如果目录不存在
				if (folder.mkdirs() == false) { 								//创建多层目录，false表示创建失败
					msg = "图片没有更新。文件存放的目录创建失败！";
					return;
				}
			}
					
			DiskFileItemFactory factory;							//磁盘文件工厂对象
			factory = new DiskFileItemFactory();
			
			ServletFileUpload upload;								//文件上传对象
			upload = new ServletFileUpload(factory);
			
			List<FileItem> listFileItem = null;						//文件元素列表
			
			try {
				listFileItem = upload.parseRequest(request);		//开始读取上传信息，得到列表	
			} catch (Exception e) {
				msg = "图片没有更新。没有有效输入！";
				return;
			}			

			novelNumber = request.getParameter("novelNumber");										//从URL中获取值			
			novelImage   = request.getParameter("novelImage");
			
			if (novelNumber.length() > 30) {													//如果是新添商品
				if (request.getSession().getAttribute("novelImage" + novelNumber) == null) {
					request.getSession().setAttribute("novelImage" + novelNumber, novelImage);			//保存到session
				}
				
				novelImage = request.getSession().getAttribute("novelImage" + novelNumber).toString();	//从session中获取值
			}
			
			for (int f = 0; f < 1; f++) {
				msg = "（无图片）";
				
				if (novelImage == null) {
					novelImage = "";
					break;
				}
				
				if (novelImage.trim().equals("")) {
					novelImage = "";
					break;
				}
				
				File file = new File(path, novelImage); 								//创建File对象
				
				if (file.exists() == false) {									//如果不存在
					novelImage = "";
					break;
				}
				
				if (file.isDirectory()) {										//如果是文件夹
					if (file.delete() == false) {
						msg += "删除同名的文件夹失败。";
						novelImage = "";
						break;
					}
				}

				uploadFolder = uploadFolder.replace("\\", "/");					// 将\替换为/

				String urlImage = uploadFolder + novelImage + "?t=" + (new Date()).getTime();	//加上时间参数以显示最新图片
				msg = "<a href='" + urlImage + "' target='_blank'><img src='" + urlImage + "' height='100'></a>";
				
				if (novelNumber.length() < 30) { 
					msg += "<div style='margin-top:60px;'>&emsp;&emsp;&emsp;&emsp;";
					msg += "&emsp;&emsp;（<a href='GoodsShow?novelNumber=" + novelNumber + "' target='_top'>详情</a>";
				}
			}
			
			for (FileItem fileItem: listFileItem) {					//对于每一个对象
				
				if (fileItem.isFormField()) {						//如果是表单字段
					continue;										//执行下一轮循环
				}
				//---------往下：得到的是文件对象了
				
				long size = fileItem.getSize();						//文件大小			
				size = (size + 1023) / 1024;						//转换为KB。如果1<=size<=1024，则结果为1
							
				if (size > 2 * 1024) {
					msg = "图片没有更新。上传的图片的大小不能超过2M。";
					break;
				}
				
				String fileName = fileItem.getName();				//文件名，而IE浏览器返回的是文件的整个路径
				
				if (fileName.equals("")) {							//未选择文件
					continue;
				}
					
				int index = fileName.lastIndexOf("\\");				//路径中最后一个“\”的位置
				if (index >= 0)	{									//如果有“\”（对于IE浏览器）
					fileName = fileName.substring(index + 1);		//获取最后的文件名（对于IE浏览器）
				}
								
				index = fileName.lastIndexOf(".");					//路径中最后一个“.”的位置

				if (index == -1)	{								//没有“.”
					msg = "图片没有更新。请上传图片文件。";
					break;
				}					
				
				if (index >= 0)	{													//如果有“.”
					String nameExt = fileName.substring(index + 1).toLowerCase();	//获取文件的扩展名，并转换为小写字母						
					String nameExtAll = ",jpg,jpeg,png,gif,bmp,";					//允许上传的图片类型
					
					if (nameExtAll.indexOf("," + nameExt + ",") == -1) {			//如果前者没包含后者						
						msg = "图片没有更新。请上传jpg,jpeg,png,gif,bmp类型图片。";
						break;
					}

					imageNew = novelNumber + "." + nameExt;				//新上传图片的名称
																	//加上时间参数以使在页面上显示最近上传的图片
					String urlImage = uploadFolder + imageNew + "?t=" + (new Date()).getTime();		//加上时间参数以显示最新图片
					msg = "<a href='" + urlImage + "' target='_blank'><img src='" + urlImage + "' height='100'></a>";
					
					if (novelNumber.length() < 30) {	
						msg += "<div style='margin-top:60px;'>&emsp;&emsp;&emsp;&emsp;<span style='color:red;'>图片更新成功！</span>";
						msg += "&emsp;&emsp;（<a href='GoodsShow?novelNumber=" + novelNumber + "' target='_top'>详情</a>";

					}
				}
				
				File fileNew = new File(path, imageNew);			//创建File对象
				
				if (fileNew.exists()) {								//如果已存在同名文件，应先删除它
					if (fileNew.delete() == false) {				//如果删除失败
						msg = "图片没有更新。与上传文件同名的文件已存在，但在将已有文件删除时失败。";
						continue;
					}
				}
					
				fileItem.write(fileNew);							//将缓冲的文件以file的名称和位置保存到磁盘
				
				if (fileNew.exists()) {								//如果文件已上传成功
					if (imageNew.equals(novelImage) == false) {			//如果新文件名与旧文件名不相同
					
						if (novelNumber.length() > 30) {				//如果是新添商品
							request.getSession().setAttribute("novelImage" + novelNumber, imageNew);		//保存到session
							
						} else {									//如果是修改商品
							dao.novelDao novelDao = new dao.novelDao();

							int count = novelDao.update(request, novelNumber, imageNew);			//****更新数据表中的image字段
							
							if (count == 0) {
								msg += "图片没有更新。数据表中的商品图片修改失败！请重试。";
								continue;
							}
						}
						
						if (novelImage.equals("") == false) {			//如果旧文件名非空
							File fileOld = new File(path, novelImage);	//创建File对象
						
							if (fileOld.exists()) {					//如果该文件存在，应删除它
								if (fileOld.delete() == false) {	//如果删除失败
									msg = "将旧文件删除时失败。";
									continue;
								}
							}
						}
						
						novelImage = imageNew;							//更新图片名称
					}
				}
			}
						
		} catch (Exception e) {
			msg += "图片没有更新。系统发生错误。";	
			e.printStackTrace();
		} finally {			
			request.setAttribute("msg", msg);	
			
			action  = "novelImageUploadDo?novelNumber=" + novelNumber + "&novelImage=" + novelImage;
			request.setAttribute("action", action);
			
			request.getRequestDispatcher(url).forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
